<template>
  <div class="floor flex" ref="floorTarget">
    <div class="avatar-container">
      <el-avatar :size="40" :src="reComment.authorAvatar"/>
    </div>
    <div class="con m-l-16 flex-1" style="min-width: 0;">
      <div class="flex align-items-center content-space-between p-b-5">
        <router-link
          :to="`/${$rp.USERS}/${reComment.authorId}`"
          class="title link"
          v-text="reComment.authorNickname"
        />
        <span
          v-if="reComment.authorId === curUser.id && !edit"
          class="link el-link--primary m-r-16"
          @click="edit = true"
          v-text="'编辑'"
        ></span>
      </div>
      <template v-if="!edit">
        <div class="p-y-2 ">
          <div v-html="emojiFormat(reComment.content)"></div>
        </div>
        <div class="info f-mini">
          <timeago2 :date-time="commentTime.time" :pre-text="commentTime.pre" />
          <VoteIcons :comment.sync="reComment"/>
          <span class="f-mini m-l-16 link primary-hover-color" @click="replyMainFloor">回复</span>
        </div>
      </template>
      <template v-else>
        <comment-edit
          :key="`${reComment.id}-edit`"
          :edit.sync="edit"
          :floor="reComment"
          v-on:updatedComment="updatedComment"
        />
      </template>
      <div v-if="subFloors.length || isLoading" class="sub-floors" v-loading="isLoading">
        <SubFloor
          v-for="comment in subFloors"
          :key="comment.id"
          :comment="comment"
          v-on:replySubFloor="replySubFloor"
        />
      </div>
      <div
        v-if="!subFloorDisplay && reComment.subsCount > 0"
        class="f-mini info-deep flex align-items-center"
      >
        共{{ reComment.subsCount }}条回复，
        <span class="el-link el-link--primary is-underline f-mini" @click="queryFloor">点击查看</span>
      </div>
      <pagination
        :current-page="pagination.currentPage"
        :page-count="pagination.pageCount"
        :is-mini="true"
      />
      <FloorReply
        v-if="receiveInfo.commentId"
        v-show="receiveInfo.enable"
        ref="floorReply"
        :placement="placement"
        :placement-id="placementId"
        :floor-comment-id="reComment.id"
        :receive-user-id="receiveInfo.userId"
        :receive-user-nickname="receiveInfo.userNickname"
        :receive-comment-id="receiveInfo.commentId"
        v-on:commentSuccess="commentSuccess"
      />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import EmojiMixin from '@/components/emoji/emoji-mixin';
import VoteIcons from './VoteIcons';
import SubFloor from './SubFloor';
import FloorReply from './FloorReply';
import CommentEdit from './comment-edit';
import * as format from './format';

export default {
  name: 'MainFloor', // 主楼层
  mixins: [EmojiMixin],
  components: { VoteIcons, SubFloor, FloorReply, CommentEdit },
  props: {
    comment: { // 这层楼的数据
      type: Object,
      required: true,
    },
    placement: { // 是哪个位置调用了评论区，楼中楼回复看似不需要实际在获取讨论个数的时候需要
      type: String,
      required: true,
    },
    placementId: { // 调用的位置的id
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      reComment: this.comment, // 复制一遍，避免点赞后更新数据时报错
      subFloorDisplay: this.$route.query.comment_id === this.comment.id, // 是否展开楼中楼
      subFloors: [], // 楼中楼数据
      isLoading: false, // 正加载楼中楼
      receiveInfo: { // 在启用楼层回复时，“回复给谁”
        enable: false, // 是否点击了“回复”按钮，激活输入框准备回复了
        commentId: undefined, // 准备回复哪个评论
        userId: this.comment.authorId, // 准备回复的评论时谁发的（给谁提醒）
        userNickname: this.comment.authorNickname, // 准备回复的评论时谁发的
      },
      pagination: { // 翻页组件
        currentPage: null, // 当前页
        pageCount: null, // 总页数
      },
      edit: false, // 编辑模式
    };
  },
  computed: {
    ...mapState({ curUser: 'currentUser' }),
    // 加载楼中楼所需参数
    initLoadSubFloorsParams() {
      return {
        commentId: Number(this.$route.query.comment_id),
        page: this.$route.query.sub_page || 1,
      };
    },
    commentTime() {
      const createdAt = new Date(this.reComment.created_at).getTime();
      const updatedAt = new Date(this.reComment.updated_at).getTime();
      if (createdAt < updatedAt - 1000) return { time: this.reComment.updated_at, pre: '编辑于 ' };
      return { time: this.reComment.created_at };
    },
  },
  methods: {
    // 回复主楼
    replyMainFloor() {
      this.receiveInfo.userId = this.reComment.authorId;
      this.receiveInfo.userNickname = this.reComment.authorNickname;
      if (this.receiveInfo.commentId !== this.reComment.id || !this.receiveInfo.enable) {
        this.receiveInfo.commentId = this.reComment.id;
        this.receiveInfo.enable = true;
      } else this.receiveInfo.enable = false;
    },
    // 回复楼中楼
    replySubFloor(info) {
      this.receiveInfo.commentId = info.commentId;
      this.receiveInfo.userId = info.userId;
      this.receiveInfo.userNickname = info.userNickname;
      this.receiveInfo.enable = true;
    },
    // 回复主楼成功
    commentSuccess(comment) { this.subFloors.push(comment); },
    // 在url中添加当前查看的楼中楼的数据
    queryFloor() {
      const oldQuery = this.$route.query;
      const newQuery = Object.assign(JSON.parse(JSON.stringify(oldQuery)), {
        comment_id: this.reComment.id, // 当前楼的id
        sub_page: undefined, // 楼中楼页数归零
      });
      this.$root.$emit('routerPush', { query: newQuery, force: true });
    },
    // 加载楼中楼
    loadSubFloors() {
      this.isLoading = true;
      this.subFloorDisplay = true;
      this.$api.comments.subIndex(this.initLoadSubFloorsParams)
        .then((res) => {
          this.subFloors = format.formatComments(res.data);
          this.pagination.currentPage = res.kaminari.current_page;
          this.pagination.pageCount = res.kaminari.total_pages;
        })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
    // 当通过消息提醒跳过来时，获取焦点
    getFocus() {
      const currentSubFloor = this.reComment.id === Number(this.$route.query.comment_id);
      if (currentSubFloor) this.$refs.floorTarget.scrollIntoView({ block: 'center' });
    },
    updatedComment(comment) { this.reComment = comment; },
  },
  created() {
    if (this.initLoadSubFloorsParams.commentId === this.reComment.id) this.loadSubFloors();
  },
  mounted() { this.getFocus(); },
  watch: {
    // 监听加载楼中楼的参数，如果是当前楼层加载，则去请求数据
    initLoadSubFloorsParams() {
      if (this.initLoadSubFloorsParams.commentId === this.reComment.id) this.loadSubFloors();
    },
    // 监听回复人数据，当点开回复时，聚焦到输入框
    receiveInfo: {
      handler() {
        this.$nextTick(() => {
          const floorReply = this.$refs.floorReply;
          floorReply.$el.scrollIntoView({ block: 'center' });
        });
      },
      deep: true,
    },
  },
};
</script>

<style lang="scss">
.floor {
  >.avatar-container {
    margin-top: 1.5rem;
    margin-left: .3125rem;
  }

  >.con {
    border-top: 1px solid #e5e5e5;
    padding-top: 1.5rem;
    padding-bottom: 1rem;
    min-width: 0;
  }
}
.floor:last-child>.con { border-bottom: 1px solid #e5e5e5; }

.sub-floors { min-height: 3rem; }
</style>
